﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ConsoleApp
{
    public class demo_pling
    {
        public static void demo()
        {
            /*
             * 利用PLing求100000以内的素数
             */
            IEnumerable<int> numbers = Enumerable.Range(3, 100000 - 3);
            var cancelSource = new CancellationTokenSource();
            var primeNumberQuery = from n in numbers.AsParallel().WithCancellation(cancelSource.Token)
                                   where Enumerable.Range(2, (int)Math.Sqrt(n)).All(i => n % i > 0)
                                   select n;
            new Thread(() =>
            {
                Thread.Sleep(100);      // Cancel query after
                cancelSource.Cancel();
            }).Start();

            try
            {
                int[] primes = primeNumberQuery.ToArray(); // Start query running:
                // We'll never get here because the other thread will cancel us.
            }
            catch (OperationCanceledException)
            {
                Console.WriteLine("Query canceled");
            }
        }
    }
}
